package com.ggkt.module.organizationalStruture.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ggkt.module.organizationalStruture.dao.OrganizationalStructureDao;
import com.ggkt.module.organizationalStruture.domain.*;
import com.ggkt.module.organizationalStruture.entity.ResultBean;
import com.ggkt.module.organizationalStruture.service.OrganizationTreeService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Component
@Slf4j
@RestController
@MapperScan("com.*.organizationalStruture.dao") //mapper扫描
@RequestMapping(value = "/organization")
public class OrganizationalStructureCtrl {
    @Autowired
    private OrganizationalStructureDao orgStructDao;

    @Autowired
    private OrganizationTreeService treeService;

    @RequestMapping("/demo")
    public void demo()throws Exception{
        System.out.println("this is demo in org");
    }

    int i ,j= 0;
    /**
     * 根据corpId获取公司下的部门
     * @param
     * @return
     */
    @PostMapping("/findDepts/{parentId}")
    public ResultBean deptList(@PathVariable("parentId") Integer parentId) throws Exception{
        ResultBean resultBean = new ResultBean();
        try{
            String corpId= Dictionary.CORP_ID;
            if(parentId==null){
                resultBean.setMsg("param error!");
                resultBean.setCode(ResultBean.CODE_FAIL);
                return resultBean;
            }
            List<DtDept> deptList = orgStructDao.deptList(parentId,corpId);
            resultBean.setData(deptList);
        }catch(Exception e){
            e.printStackTrace();
        }
        resultBean.setCode(ResultBean.CODE_SUCCESS);
        return resultBean;
    }
    /**
     * 根据部门id获取部门下的领导
     */
    @PostMapping("/findLeaders/{deptId}")
    public ResultBean leaderList(@PathVariable("deptId") Integer deptId) {
        ResultBean resultBean = new ResultBean();
        try{
            String corpId=Dictionary.CORP_ID;
            List<DingtalkUsers> deptList = orgStructDao.userList(deptId,corpId);
            resultBean.setData(deptList);
        }catch(Exception e){
            e.printStackTrace();
        }
        return resultBean;
    }
    /**
     * 领导统管的小组
     */
    @PostMapping("/findGroupsByLeader")
    public ResultBean groupList(){
        ResultBean resultBean = new ResultBean();
        try{
            String corpId=Dictionary.CORP_ID;;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 组织架构树
     * @return
     */
    @RequestMapping(value = "/treeList",method = {RequestMethod.POST,RequestMethod.GET})
    public ResultBean treeList() {
        long start_time=System.currentTimeMillis();
        ResultBean resultBean = new ResultBean();
        QueryWrapper<DtDept> queryWrapper=new QueryWrapper<DtDept>();
        DtDept entity=new DtDept();
        queryWrapper.setEntity(entity);
        queryWrapper.eq("corpId",Dictionary.CORP_ID);
        queryWrapper.eq("logicStatus",1);
        queryWrapper.orderByAsc("orgOrder");
        //查出所有部门数据；
        List<DtDept> deptList = treeService.list(queryWrapper);
        //查询所有用户数据，准备拼装到对应的组织中
        List<DingtalkUsers> userList = new ArrayList<DingtalkUsers>();
        try {
            userList = orgStructDao.getUsersByCorpId(Dictionary.CORP_ID);
            System.out.println("userList size is :"+userList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //实例化OrganizationTree,元素为DtDept扩展对象OrganizationTree
        LinkedList<OrganizationTree> deptTreeList = new LinkedList<OrganizationTree>();
        //对部门数据重新组装，循环deptList
        for (DtDept dept : deptList) {
            if (dept.getParentId() != null && dept.getParentId()== 1) {
                //将公司的一级部门拷贝到OrganizationTree对象中
                OrganizationTree organizationTree = new OrganizationTree(dept);
                //遍历整个部门数据将部门树状结构赋值给当前部门OrganizationTree对象
                buildDeptTree(organizationTree, deptList,userList);
                deptTreeList.add(organizationTree);
            }
            i++;
        }
        System.out.println("部门循环次数"+i);
        System.out.println("部门组装开始时间："+start_time );
        System.out.println("部门组装结束时间："+System.currentTimeMillis());
        //重新组装后的deptTreeList作为结果集返回
        resultBean.setData(deptTreeList);
        return resultBean;
    }
    /**
     * 构建组织架构树
     * @param organizationTree
     * @param deptList
     * @param userList
     */
    private void buildDeptTree(OrganizationTree organizationTree, List<DtDept> deptList,List<DingtalkUsers> userList) {
        LinkedList<OrganizationTree> children = new LinkedList<OrganizationTree>();

        System.out.println("orgId===: "+organizationTree.getOrgId());
        for (DtDept dept : deptList) {
            //实例化用户list，将组织下的数据存入此对象，最后赋值给这个组织；
            LinkedList<DingtalkUsers> deptUserList = new LinkedList<DingtalkUsers>();
            if (organizationTree.getOrgId().equals(dept.getParentId())) {
                //如果list中部门的上级部门是organizationTree,则把对象放到当前部门的children对象中
                OrganizationTree childMenu = new OrganizationTree(dept);

                //获取当前部门下的用户数据，将部门用户赋值给当前OrganizationTree;
                for(DingtalkUsers user:userList){
                    if(childMenu.getOrgId().equals(user.getMainDeptId())){
                        System.out.println("main_dept_id is: "+user.getMainDeptId());
                        deptUserList.add(user);
                    }
                }
                System.out.println("deptUserList is: "+deptUserList.size());
                childMenu.setDeptUsers(deptUserList);
                if(deptUserList.size()>0){
                    System.out.println("有员工的部门ID为： "+childMenu.getOrgId());
                }
//                deptUserList=null;
//                deptUserList=new LinkedList<DingtalkUsers>();
                //递归调用当前方法，直到循环的部门没有上级部门为止;
                buildDeptTree(childMenu, deptList,userList);
                children.add(childMenu);
            }
            j++;
        }
        //System.out.println("部门Tree循环次数"+j);
        //如果children有数据则，把children赋值给入参organizationTree对象；
        if (children.isEmpty() == false) {
            organizationTree.setChildren(children);
        }
    }

    /**
     * 根据部门deptId统计部门下的工龄分布情况
     * @param deptId
     * @return
     */
    @PostMapping("/statistics/workTime/{deptId}")//dept=117060476
    public ResultBean statisticsWorkTime(@PathVariable("deptId") Integer deptId){
        ResultBean resultBean = new ResultBean();
        String corpId=Dictionary.CORP_ID;
        try {
            List<WorkTimeStatistics> staticList = orgStructDao.workTimeList(corpId, deptId);
            Integer totalNum = 0;
            for(WorkTimeStatistics statis:staticList){
                totalNum+=statis.getCount();
            }
            for(WorkTimeStatistics statist:staticList){
                System.out.println("count is: "+statist.getCount());
                Float ratioTmp = (float)(100*statist.getCount()/totalNum)/100;
                System.out.println("totalNum is: "+totalNum);
                System.out.println("ratioTmp is: "+ratioTmp);
                statist.setRatio(ratioTmp*100/100);
            }
            resultBean.setData(staticList);
        }catch(Exception e){
            e.printStackTrace();
        }
        return resultBean;
    }

    /**
     * 统计部门下在岗装态,正式、试用期、待返岗；
     */
    @PostMapping("/statistics/workStatus/{deptId}")//dept=117060476
    public ResultBean statisticsWorkStatus(@PathVariable("deptId") Integer deptId){
        ResultBean resultBean = new ResultBean();
        String corpId=Dictionary.CORP_ID;
        try{
            List<WorkStatusStatistics> userInOfficeList = orgStructDao.getUserWorkStatusByOrgId(corpId, deptId);
            resultBean.setData(userInOfficeList);
        }catch(Exception e){
            e.printStackTrace();
        }
        return resultBean;
    }
}
